package com.abe.libcore.utils

import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.ThreadFactory
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger


object ThreadPoolUtils {
    // 线程池当前运行数
    private const val CORE_POOL_SIZE: Int = 5
    // 线程池最大线程数
    private const val MAX_POOL_SIZE: Int = 100
    // 额外线程最长生存时间
    private const val KEEP_ALIVE_TIME: Long = 0
    
    private val workQueue = ArrayBlockingQueue<Runnable>(10)
    /*
     * 线程工厂
     */
    private val threadFactory = object : ThreadFactory {
        private val integer = AtomicInteger()// AtomicInteger 是线程安全的 ，而且性能超用synchronized的方法

        override fun newThread(r: Runnable): Thread {
            return Thread(r, "myThreadPool thread:" + integer.getAndIncrement())
        }
    }
    // 线程池
    private val threadPool: ThreadPoolExecutor? = ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, workQueue, threadFactory)

    fun execute(r: Runnable) {
        threadPool!!.execute(r)
    }
}